﻿import serial
import math
import os
import serial.tools.list_ports
# from collections import Counter
import random
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import pandas as pd

# plist = list(serial.tools.list_ports.comports())

milePort = 'com10'
ardPort = 'com5'
filename = "posDis" + str(random.uniform(0,1))

keyData = []
keyDataIndexArr = []
keyDataIndex = 0
startDis = 150

def getData(startDis):
    data = []
    peak = []
    ser = serial.Serial(milePort,115200,timeout=0.5)
    lock = False
    while(True):
        s = str(ser.readline())
        try:
            if s == "b\'Envelope data:\\n\'":
                while(True):
                    s = str(ser.readline())
                    s = s.replace("b\'", "")
                    s = s.replace("\\n\'", "")
                    if s == "end":
                        lock = True
                        break
                    temp = s.split()
                    data.extend(temp)
            if lock:
                dataLen = len(data)
                for p in data:
    	            p = int(p)
    	            peak.append(p)
                distance = [i for i in range(dataLen)]
                distance = np.trunc(np.array(distance) * 0.484).astype(np.int16)
                ser.close()
                return distance, peak
        except ValueError:
                print("Test again!")
                ser.close()
                break

distance = []
peak = []
peakSet = []
count = 0
pos = np.arange(1,41) * 16
ser2=serial.Serial(ardPort,115200,timeout=0.5)
while True:
    s1 = str(ser2.readline())
    if len(s1) == 6:
        distance, peak = getData(milePort)
        distance = distance[::10]
        peak = peak[::10]
        peakSet.append(peak)
        count = count + 1
        print('pos', count)
    if (count > 39):
        break
resDataframe = pd.DataFrame(peakSet, index = pos, columns = distance)
sns.heatmap(resDataframe, cmap='Reds')
plt.show()